<template>
  <div>
    <!-- 文章列表 -->
    <div class="page_title">
      <h1>文章管理</h1>
      <el-button type="primary" @click="toOpen">添加文章</el-button>
    </div>
    <!--  添加布局 -->
      <el-drawer
        v-model="drawer"
        :title="mytitle"
        :direction="direction"
        size="50%"
      >
         <el-form :model="formModel" ref="myform">
          <el-form-item label="文章标题">
            <el-input v-model="formModel.title"></el-input>
          </el-form-item>
          <el-form-item label="文章分类">
            <el-select 
               v-model="formModel.cate_id">
               <el-option v-for="item in cateList" :key="item.id"
                :label="item.cate_name"
                :value="item.id"
               >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章封面">
             <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :on-change="selectImg"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
          </el-form-item>
          <el-form-item label="文章封面">
             <!-- 富文本编辑器 -->
               <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                />
                <Editor
                  style="width:100%;height: 200px; overflow-y: hidden;"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  @onCreated="handleCreated"
                />
          </el-form-item> 
          <el-form-item style="padding-left:50px;">
              <el-button type="primary" @click="toAdd('已发布')">发布</el-button>
             <el-button type="success" @click="toAdd('草稿')">草稿</el-button>
          </el-form-item>
         </el-form>
    </el-drawer>
    <div id="table_wrap">
        <el-form  label-width="120px">  
          <el-form-item label="文章分类：">
            <el-select v-model="cate_id">
              <el-option v-for="item in cateList"
              :key="item.id"
              :value="item.id"
              :label="item.cate_name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章状态：">
             <el-select v-model="state">
              <el-option value="已发布">已发布</el-option>
              <el-option value="草稿">草稿</el-option>
            </el-select>
          </el-form-item>
         <el-form-item>
            <el-button type="primary" @click="toSearch">查询</el-button>
             <el-button type="danger" @click="toReset">重置</el-button>
         </el-form-item>
        </el-form>
        <el-table :data="tabelList">
          <el-table-column label="文章标题" prop="title">
          </el-table-column>
              <el-table-column label="文章分类" prop="cate_name">
          </el-table-column>
              <el-table-column label="发表时间">
                <template #default="{row}">
                  {{new Date(row.pub_date).toLocaleString()}}
                </template>
          </el-table-column>
             <el-table-column label="状态" prop="state">
          </el-table-column>
             <el-table-column label="操作">
              <template #default="{row}">
                <el-button round :icon="Edit" type="primary"
                @click="toEdit(row.id)">
                    编辑
                  </el-button>
                  <el-button 
                  round :icon="Delete" 
                  type="danger" @click="toDel(row.id)">    
                    删除
                  </el-button>
            </template>    
           </el-table-column>
        </el-table>
        <div class="page">
         <el-pagination
            v-model:current-page="currentPage4"
            v-model:page-size="pageSize4"
            @size-change="sizeChange"
            @current-change="pageChange"
            :page-sizes="[2, 4, 6, 10]"
            background
            prev-text="前按钮"
            layout="jumper,total, sizes, prev,pager,next"
            :total="total"
          />
        </div>
    </div>
  </div>
</template>

<script setup lang="ts">    

// npm i 插件  安装依赖包的方式

// 全局安装 yarn 插件  也是安装插件的工具
// yarn 相对npm 的区别是什么 
// yarn 能自动走缓存，安装速度快
// 安装 npm i yarn -g 
// 使用yarn 插件   yarn add 插件名

    import '@wangeditor/editor/dist/css/style.css' 
    import {ref,onBeforeUnmount,shallowRef,watch} from 'vue'
    import type { DrawerProps,UploadFile,FormInstance} from 'element-plus'
    import {Plus,Delete,Edit} from '@element-plus/icons-vue'
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
    import {artGetChannelsService,artPublishService,artGetListService,artDelService,artGetDetailService,
      artEditService
    } from '@/api/aritcle.ts'
    import {baseURL} from '@/utils/request'
   // 显示隐藏控制
    let drawer=ref<boolean>(false)
    // 方向控制
    const direction = ref<DrawerProps['direction']>('rtl')
    // 缩略图地址
    let imageUrl=ref('')
    // 弹出层标题
    let mytitle=ref('添加文章')

     // 编辑器实例，必须用 shallowRef
    // shallowRef 和ref的区别是 shallowRef是浅响应式
    // shallowReactive() 浅响应式的 reactive 
    
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>')
    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })
    const handleCreated = (editor:any) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    let toOpen=()=>{
      drawer.value=true;
    }
    // 添加操作
    let formModel=ref<any>({
        title:"", //文章标题
        cate_id: "", //分类id
        cover_img: "", //图片的二进制
        content: "", //文章内容
        state:"" //文章状态
    })
    // 获取分类列表给下拉框赋值
    let cateList=ref<any>([])
    artGetChannelsService().then((res:any)=>{
      console.log(res,"--------------")
      cateList.value=res.data;
    })

    // 文件上传框的 change事件
    let selectImg=(upFile:UploadFile)=>{
      // UploadFile 是从elementplus库导出的type类型
      console.log(upFile.raw,"-----------")
      imageUrl.value=URL.createObjectURL(upFile.raw as Blob)
      formModel.value.cover_img=upFile.raw;
    }
    // watch监听富文本编辑器值的变化 获取富文本的值
      watch(valueHtml,(newVal:any)=>{
        formModel.value.content=newVal;
      })

      // 调用添加接口方法
      let toAdd=async (state:string)=>{
        formModel.value.state=state; //文章状态
          console.log(formModel.value,"*********")
          let formdata=new FormData();
          for(let key in formModel.value){
              // key-------value
              formdata.append(key,formModel.value[key])
          }
          console.log(formdata,"666666666666")

          if(formModel.value.id){ //如果有修改id
                // 编辑文章接口的调用
             let editRes=await artEditService(formdata)
            if(editRes.code==0){
               ElMessage.success("编辑文章成功！")
            }
              
          }else{
                  // 添加文章接口 

                let res=await artPublishService(formdata);
                console.log(res,"---------")
                if(res.code==0){
                  ElMessage.success("发布文章成功！")
                }
          }
         mytitle.value="添加文章"
         formModel.value.id=""; //清空编辑id
          let myform=ref<FormInstance>(); //获取表单组件
          // 获取表单组件  调用组件自带的重置方法
          // if(myform.value){
          //    myform.value.resetFields()
          // }
          formModel.value.title=""
          formModel.value.content=""
          formModel.value.cate_id=""
          imageUrl.value=''
          valueHtml.value=""//富文本的清空
          // 添加成关闭弹出层
           drawer.value=false;
          //  添加完成 重新获取列表
           getList();

      }
 //  ---------获取列表--------------------------------------------
    //当前页码
    const currentPage4 = ref(1)
    // 每页条数
    const pageSize4 = ref(10)
    let cate_id=ref(''); //分类查询条件
    let state=ref('')//状态查询条件
    let tabelList=ref([]);//列表数据
    let total=ref(0)//数据总条数
    //
      let getList=async ()=>{

        let res=await  artGetListService({
          pagenum:currentPage4.value, //当前页码
          pagesize:pageSize4.value, //每页条数
          cate_id:cate_id.value, //分类id
          state:state.value //发布状态
        })
        console.log(res,"5555555555555555555")
        tabelList.value=res.data;
         total.value=res.total; //数据总条数

      }
      getList();
      // 搜索和分页功能
      let toSearch=()=>{
           getList();
      }
      // 重置
      let toReset=()=>{
        cate_id.value=''
        state.value=''
      }
      // 分页的change事件
      let pageChange=(val:any)=>{ 
        currentPage4.value=val;//改变当前页码
          getList();
      }
      // 分页组件的 size 改变事件 一页条数改变
      let sizeChange=(val:any)=>{
        console.log(val,"---")
        pageSize4.value=val;
          getList();
      }
  // 删除接口--------------------------------------------------
      let toDel= (id:any)=>{
         ElMessageBox.confirm(
              '您确认删除本条数据吗',
              '重要提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
          }).then(async ()=>{
              let res=await artDelService(id)
                console.log(res);
                if(res.code==0){
                  ElMessage.success("删除文章成功！")
                }
                // 删除成功重新获取列表
                getList();
          })
       
      }
  // --------编辑操作-------------
    // 点击编辑 通过id 调用接口 获取回显数据
    let toEdit=async (id)=>{
      mytitle.value='编辑文章'
      let res=await artGetDetailService(id)

      console.log(res,"---------9999999999");
      drawer.value=true;
      formModel.value=res.data;
      // 图片回显  baseURL后台服务器的地址+数据返回的路径
      imageUrl.value=baseURL+res.data.cover_img;
      // 富文本编辑器的回显
      valueHtml.value=res.data.content;
    }



</script>
<style lang="scss">
    .page_title{
      display:flex;
      justify-content:space-between;
    }
    .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar{
    width: 278px;
    height: 278px;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.page{
  display:flex;
  justify-content:flex-end;
  margin-top:30px;  
}
.table_wrap{
  .el-form-item .el-form-item__content{
    width: 400px;
  }
  .el-select{
    width:300px;
  }
}
</style>